package com.lw.lost.fragments

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.lw.lost.R
import com.lw.lost.activity.LoginActivity
import com.lw.lost.activity.PersonalInfoActivity
import com.lw.lost.databinding.FragmentProfileBinding
import com.lw.lost.db.DBlost
import com.lw.lost.utils.PreferenceUtils
import java.io.File

class ProfileFragment : Fragment() {

    private var _binding: FragmentProfileBinding? = null
    private val binding get() = _binding!!
    private lateinit var db: DBlost
    private val PERMISSION_REQUEST_CODE = 100

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentProfileBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        db = DBlost(requireContext())
        
        // 检查并请求权限
        checkAndRequestPermissions()
        initClickListeners()
    }

    private fun checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13及以上
            if (requireContext().checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES)
                != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                    arrayOf(Manifest.permission.READ_MEDIA_IMAGES),
                    PERMISSION_REQUEST_CODE
                )
            } else {
                loadUserInfo()
            }
        } else {
            // Android 13以下
            if (requireContext().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                    arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                    PERMISSION_REQUEST_CODE
                )
            } else {
                loadUserInfo()
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        when (requestCode) {
            PERMISSION_REQUEST_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限获取成功，加载用户信息
                    loadUserInfo()
                } else {
                    // 权限被拒绝，显示提示
                    Toast.makeText(context, "需要存储权限来显示头像", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        // 每次页面恢复时重新加载用户信息
        loadUserInfo()
    }

    private fun loadUserInfo() {
        val userId = PreferenceUtils.getUserId(requireContext())
        val cursor = db.userDao.getUserById(userId)

        cursor.use { cursor ->
            if (cursor.moveToFirst()) {
                binding.apply {
                    tvName.text = cursor.getString(cursor.getColumnIndexOrThrow("name"))
                    
                    // 加载头像
                    val avatarPath = cursor.getString(cursor.getColumnIndexOrThrow("avatar"))
                    println("Debug: Avatar path = $avatarPath")

                    if (!avatarPath.isNullOrEmpty()) {
                        try {
                            // 将文件路径转换为 URI
                            val avatarUri = Uri.parse(avatarPath)
                            println("Debug: Avatar URI = $avatarUri")
                            
                            // 如果有头像地址，加载用户头像
                            Glide.with(this@ProfileFragment)
                                .load(avatarUri)
                                .circleCrop()
                                .placeholder(R.drawable.ic_avatar_default)
                                .error(R.drawable.ic_avatar_default)
                                .skipMemoryCache(true)
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .listener(object : RequestListener<Drawable> {
                                    override fun onLoadFailed(
                                        e: GlideException?,
                                        model: Any?,
                                        target: Target<Drawable>,
                                        isFirstResource: Boolean
                                    ): Boolean {
                                        println("Debug: Image load failed: ${e?.message}")
                                        e?.logRootCauses("ProfileFragment") // 添加详细错误日志
                                        return false
                                    }

                                    override fun onResourceReady(
                                        resource: Drawable,
                                        model: Any,
                                        target: Target<Drawable>,
                                        dataSource: DataSource,
                                        isFirstResource: Boolean
                                    ): Boolean {
                                        println("Debug: Image load success")
                                        return false
                                    }
                                })
                                .into(ivAvatar)
                        } catch (e: Exception) {
                            println("Debug: Error loading avatar: ${e.message}")
                            e.printStackTrace()
                            // 加载失败时显示默认头像
                            Glide.with(this@ProfileFragment)
                                .load(R.drawable.ic_avatar_default)
                                .circleCrop()
                                .into(ivAvatar)
                        }
                    } else {
                        // 如果没有头像地址，使用默认头像
                        Glide.with(this@ProfileFragment)
                            .load(R.drawable.ic_avatar_default)
                            .circleCrop()
                            .into(ivAvatar)
                    }
                }
            }
        }

        // 加载用户兴趣信息
        val interestCursor = db.interestDao.getInterestsByUserId(userId)
        interestCursor.use { cursor ->
            if (cursor.moveToFirst()) {
                binding.apply {
                    val education = cursor.getString(cursor.getColumnIndexOrThrow("education"))
                    val content = cursor.getString(cursor.getColumnIndexOrThrow("content"))
                    
                    tvEducation.text = "学历：$education"
                    tvInterests.text = "兴趣：$content"
                }
            }
        }
    }

    private fun initClickListeners() {
        // 个人资料点击事件
        binding.cardPersonalInfo.setOnClickListener {
            startActivity(Intent(requireContext(), PersonalInfoActivity::class.java))
        }

        // 账号设置点击事件
        binding.cardAccountSettings.setOnClickListener {
            // TODO: 跳转到账号设置页面
        }

        // 系统设置点击事件
        binding.cardSettings.setOnClickListener {
            // TODO: 跳转到系统设置页面
        }

        // 退出登录点击事件
        binding.btnLogout.setOnClickListener {
            PreferenceUtils.clearUserInfo(requireContext())
            startActivity(Intent(requireContext(), LoginActivity::class.java))
            requireActivity().finish()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 